<template>
  <div>
    <el-dialog title="更新" :model-value="updateDialogVisible" @open="handleOpen" width="30%"
      :before-close="handleCancel">
      <el-form :model="formData" :rules="rules" label-width="80px" ref="updateForm">
        <el-form-item label="系统编号:">
          <el-input v-model="formData.id" disabled></el-input>
        </el-form-item>
        <el-form-item label="用户名:" prop="username">
          <el-input v-model="formData.username"></el-input>
        </el-form-item>
        <el-form-item label="姓名:" prop="realName">
          <el-input v-model="formData.realName"></el-input>
        </el-form-item>
        <el-form-item label="性别:" prop="sex">
          <el-radio v-model="formData.sex" label="M">男</el-radio>
          <el-radio v-model="formData.sex" label="F">女</el-radio>
        </el-form-item>
        <el-form-item label="头像:" prop="avatarPath">
          <el-upload :auto-upload="true" :action="uploadCfg.uploadUrl" :show-file-list="true" list-type="picture-card"
            :on-success="handleSuccess" :on-remove="handleRemove" :limit="1" :on-exceed="handleExceed"
            :file-list="uploadInfo.fileList" :headers="uploadCfg.headers">
            <template v-slot:trigger>
              <el-icon>
                <Plus />
              </el-icon>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="onSubmit">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script setup name='UpdateUser' lang='ts'>
import { defineEmits, reactive, ref } from "vue"
import { queryByIdApi, modifyByIdApi } from "@/api/userApi"
import { ElMessage } from "element-plus";
import type { UploadFile, UploadFiles, UploadUserFile } from "element-plus";
import type { AnyObjsDefine } from '@/types/common.d.ts';
import { useUpload } from '@/hooks/useUpload'
import { useResource } from '@/hooks/useResource'


let formData = reactive({
  id: '',
  username: '',
  realName: '',
  pwd: '',
  sex: '',
  avatarPath: ''
})

let rules = reactive({
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
  ],
  realName: [
    { required: true, message: "请输入姓名", trigger: "blur" },
  ],
  pwd: [
    { required: true, message: "请输入密码", trigger: "blur" },
  ],
  sex: [
    { required: true, message: "请选择性别", trigger: "blur" },
  ],
  avatarPath: [
    { required: false, trigger: "blur" },
  ],
})

// 上传文件fileList
let uploadInfo = reactive<{
  fileList: UploadUserFile[]
}>({ fileList: [] })

let { uploadCfg, handleExceed } = useUpload()
let { toAddressable } = useResource()

const props = defineProps<{
  updateDialogVisible: boolean,
  idToUpdate: string
}>()

let emitter = defineEmits(["closeDialog", "updateSuccess"])

let updateForm = ref()

// 更新
function onSubmit() {
  updateForm.value.validate((valid: boolean) => {
    if (!valid) return
    // 执行逻辑
    modifyByIdApi(formData).then(result => {
      ElMessage({ type: "success", message: result.data })
      uploadInfo.fileList = []
      updateForm.value.resetFields()
      emitter("updateSuccess")
    })
  })
}

function handleCancel() {
  uploadInfo.fileList = []
  updateForm.value.resetFields()
  emitter("closeDialog")
}

function handleOpen() {
  queryByIdApi(props.idToUpdate).then(result => {
    Object.assign(formData,result.data)
    // 设置图片
    let addressablePath = toAddressable(result.data.avatarPath)
    if (addressablePath) {
      uploadInfo.fileList.push({ url: addressablePath, name: '' })
    }
  })
}
/*
response:后端返回的对象,file:当前上传成功的文件对象(结构a),
结构a: name,status,url(blob://),uid,size,response
fileList:包含file在内的所有已经上传成功的文件对象列表,每个file元素都是"结构a"
*/
function handleSuccess(response: any, file: UploadFile, fileList: UploadFiles) {
  if (response.success) {
    uploadInfo.fileList = fileList;
    // 业务逻辑
    formData.avatarPath = response.data
    // 清除之前校验信息
    updateForm.value.validateField('avatarPath');
  } else {
    ElMessage({ message: response.msg, type: "error" });
  }
}


//file:删除的文件(结构a)  fileList:还剩下的文件列表,每个file元素都是"结构a"
function handleRemove(file: UploadFile, fileList: UploadFiles) {
  uploadInfo.fileList = fileList;
  // 业务逻辑
  updateForm.value.avatarPath = ''
}
</script>
<style scoped></style>